package com.mate.cloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器token校验
 *
 * @author cong zhi
 * @email 448341911@qq.com
 * @createDate 2023/3/17 16:05
 * @version: v1.0
 */
@Component
public class CheckHeaderTokenGatewayGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 以token为key值
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if ("bearer".equals(token)) {
            return chain.filter(exchange);
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    /**
     * order值越小，执行的优先级就越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
